package com.dycong.common.database.redis;

import com.google.common.base.Strings;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.util.Pool;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class JedisPoolFactoryBean extends AbstractFactoryBean<Pool<Jedis>> {

    private String mode;

    private int database;

    // for single
    private String host;

    // for single
    private int port;

    private String password;

    private int timeout;

    // for sentine
    private String sentinelHosts;

    // for sentine
    private String masterName;

    private JedisPoolConfig jedisPoolConfig;

    @Override
    public Class<?> getObjectType() {
        return Pool.class;
    }

    @Override
    protected Pool<Jedis> createInstance() throws Exception {
        if ("single".equals(mode)) {
            return new JedisPool(jedisPoolConfig, host, port, timeout, Strings.isNullOrEmpty(password) ? null : password, database);
        } else if ("sentine".equals(mode)) {
            Set<String> set = new HashSet<String>(Arrays.asList(sentinelHosts.split(",")));
            return new JedisSentinelPool(masterName, set, jedisPoolConfig, timeout, Strings.isNullOrEmpty(password) ? null : password, database);
        } else {
            throw new RuntimeException("unsupport mode");
        }
    }

}
